﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mime;

namespace NHINDirect
{
    public abstract class MultipartEntity : IEnumerable<MimeEntity>
    {
        ContentType m_contentType;

        public MultipartEntity()
            : this(Protocol.MultiPartType_Mixed)
        {
        }
        
        public MultipartEntity(string contentType)
            : this(new ContentType(contentType))
        {
        }
        
        public MultipartEntity(ContentType contentType)
        {
            this.ContentType = contentType;
        }
        
        public ContentType ContentType
        {
            get
            {
                return this.m_contentType;
            }       
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException();
                }
                
                this.m_contentType = value;
                this.EnsureBoundary();
            }     
        }
        
        public string Boundary
        {
            get
            {
                return this.m_contentType.Boundary;
            }
        }

        public MimeEntity ToEntity()
        {
            MimeEntity entity = new MimeEntity();
            entity.SetParts(this, this.m_contentType.ToString());
            return entity;
        }

        public abstract IEnumerator<MimeEntity> GetEnumerator();
        
        void EnsureBoundary()
        {
            if (string.IsNullOrEmpty(this.m_contentType.Boundary))
            {
                this.m_contentType.Boundary = Guid.NewGuid().ToString("N");
            }
        }
        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion
    }
}
